package com.example.nio02;


import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * @Date 2022/10/7
 * @Author Jonathan
 */
public class NioDemo04 {


    @Test
    public void test() {
        System.out.println("hello world");
    }


    /**
     * buffer转换成字符串
     */
    @Test
    public void test01() {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        buffer.put("青春".getBytes(StandardCharsets.UTF_8));
        buffer.flip();
        CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer);
        System.out.println("result is:" + charBuffer);
    }


    /**
     * 将字符串写入文件
     */
    @Test
    public void test02() throws IOException {
        FileChannel channel = new FileOutputStream("data1").getChannel();
        ByteBuffer buffer = StandardCharsets.UTF_8.encode("爱情");
        channel.write(buffer);
    }


    /**
     * 文件拷贝以及大文件拷贝
     * NIO文件拷贝上限是2G
     */
    @Test
    public void test03() throws IOException {
        FileChannel from = new FileInputStream("D:\\code\\example\\netty-learn\\data1").getChannel();
        FileChannel to = new FileOutputStream("D:\\code\\example\\netty-learn\\data2").getChannel();
        // NIO文教拷贝效率高
        //from.transferTo(0, from.size(), to);

        //  对于超过2G的文件拷贝
        long left = from.size();
        while (left > 0) {
            left -= from.transferTo(from.size() - left, left, to);
        }
    }

}
